<script lang="ts" setup>
import { getSpeInfoApi, getSpesApi } from "@/api/activity";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  rules: {
    type: Array,
    default: () => {
      return [];
    },
  },
  goodsId: {
    type: Number,
  },
  prefix: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["update:modelValue"]),
  formRef = inject("formRef");

const specList = ref<Array<any>>([]);

const detail = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val) => {
    emits("update:modelValue", val);
  },
});

watch(
  () => props.goodsId,
  (val) => {
    if (val) {
      nextTick(() => {
        getSpecList();
      });
    }
  },
  { immediate: true }
);

watch(
  () => props.modelValue.goodsSpeId,
  (val) => {
    if (val) {
      nextTick(() => {
        initSpecStock();
      });
    }
  },
  { immediate: true }
);

const initSpecStock = async () => {
  let specDetail = await getSpecDetail(props.modelValue.goodsSpeId);
  if (specDetail) detail.value.specStock = specDetail.beforeStock;
  onChange();
};

// 切换规格
const changeSpec = async () => {
  const info = await getSpecDetail(detail.value.goodsSpeId);
  if (info) {
    detail.value.thumbnailUrl = info.thumbnailUrl;
    detail.value.name = info.name;
    detail.value.specStock = info.beforeStock;
    detail.value.costPrice = info.costPrice ?? info.payPrice
  }
  onChange();
  nextTick(() => {
    formRef?.value?.validateField(`${props.prefix}thumbnailUrl`);
  });
};

const getSpecList = async () => {
  const rs = await getSpesApi({ id: props.goodsId });
  if (rs.code == 200) {
    specList.value = rs.payload || [];
  }
};

const getSpecDetail = async (id: string | number) => {
  const rs = await getSpeInfoApi({ id });
  if (rs.code == 200) {
    return rs.payload;
  }
  return null;
};

const onChange = () => {
  detail.value = detail.value;
};
</script>
<template>
  <el-form-item label="商品规格" :prop="`${prefix}goodsSpeId`" :rules="[
    ...rules,
    {
      required: true,
      message: '请选择商品规格',
      trigger: 'change',
    },
  ]">
    <el-select v-model="modelValue.goodsSpeId" placeholder="请选择商品规格" :disabled="disabled" @change="changeSpec">
      <el-option v-for="item in specList" :label="item.name" :value="item.id" />
    </el-select>
    <span v-if="detail.goodsSpeId">&nbsp;&nbsp;剩余库存：<span class="mark-text">{{
      detail.specStock
    }}</span>&nbsp;件</span>
  </el-form-item>
</template>
